package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j2
public class WmMaterialServiceImpl  extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        WmMaterial wmMaterial =new WmMaterial();
        try{
            //1.检查参数
            if(multipartFile == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            String filePath = fastDFSClientUtil.uploadFile(multipartFile);

            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setUrl(filePath);
            WmUser user = WmThreadLocalUtils.getUser();
            if(user!=null){
                wmMaterial.setUserId(user.getId());
            }

            save(wmMaterial);
            //拼接图片路径
            wmMaterial.setUrl(fileServerUrl+filePath);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        //1.检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();

        // IsCollection  日期倒序
        LambdaQueryWrapper<WmMaterial> queryWrapper =new LambdaQueryWrapper<>();
        if(dto.getIsCollection() ==1){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        Page pageParam = new Page(dto.getPage(),dto.getSize());
        IPage resultPage = page(pageParam, queryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)resultPage.getTotal());


        List<WmMaterial> list = resultPage.getRecords();
        list = list.stream().map(a->{
            a.setUrl(fileServerUrl.concat(a.getUrl()));
            return a;
        }).collect(Collectors.toList());

//        for(WmMaterial w: list){
//            w.setUrl(fileServerUrl.concat(w.getUrl()));
//        }
        responseResult.setData(list);

        return responseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {

        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断当前素材是否被引用
        QueryWrapper<WmNewsMaterial> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("material_id",id);
        //queryWrapper.lambda().eq(WmNewsMaterial::getMaterialId,id);
        Integer selectCount = wmNewsMaterialMapper.selectCount(queryWrapper);
        if(selectCount>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //删除逻辑  删图片fastdfs   删数据
        fastDFSClientUtil.delFile(wmMaterial.getUrl());
        boolean b = removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {

        // update wm_material set is_collection= ? where id=? and user_id=?
        Integer userId = WmThreadLocalUtils.getUser().getId();
        if(id !=null && userId!=null){
            //Wrapper<WmMaterial> wrapper =new UpdateWrapper<>();
            //Wrappers.lambdaUpdate().set(wmm)

            this.update((Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type)
                    .eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId)));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}
